<template>
  <h1>注册</h1>
  <el-icon :size="20">
    <Edit />
  </el-icon>
  <Edit style="width: 1em; height: 1em; margin-right: 8px" />
  <el-card>
    <!-- 表单组件 -->
    <el-form
      ref="form"
      :model="userInfo"
      status-icon
      label-width="120px"
      class="demo-ruleForm"
      :rules="rules"
    >
      <!--  用户名 -->
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="userInfo.userName" type="text" autocomplete="off" />
      </el-form-item>
      <!-- 用户密码 -->
      <el-form-item label="Password" prop="passWord">
        <el-input
          v-model="userInfo.passWord"
          type="password"
          autocomplete="off"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm"> Submit </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { ElMessage } from "element-plus";
import service from "./service";
export default {
  data() {
    return {
      userInfo: {
        userName: "",
        passWord: "",
      },
      rules: {
        userName: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur",
          },
          {
            min: 1,
            max: 7,
            message: "用户长度1-7",
            trigger: "blur",
          },
        ],
        passWord: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
          {
            min: 1,
            max: 7,
            message: "用户长度1-7",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    async submitForm() {
      const res = await this.$refs.form.validate();
      if (!res) return false;
      const { userName, passWord } = this.userInfo;
      const data = await service.Reg(userName, passWord);
      const { code, msg } = data || {};
      if (code) {
        ElMessage.error(msg);
        return false;
      }
      console.log(token);
      ElMessage.success({
        onClose: () => {
          this.$router.replace("/home");
        },
        duration: 1000,
        message: "注册成功 3s跳转首页",
        type: "success",
      });
      localStorage.setItem("token", token);
    },
  },
};
</script>
